﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Management;
using System.Data;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections;
using System.IO;
using System.Text;
using System.Net;

public class MachineCode
{

    /// <summary>
    /// 获取机器配置信息
    /// </summary>
    /// <returns></returns>
    public static string GetMachineConfig(string str)
    {
        string strCmd = "ipconfig /all";//要执行的命令
        string procName = "cmd.exe";
        string rtnStr = "";
        try
        {
            List<string> rstList =new List<string>(); 
            rstList= executeCmd(strCmd, procName);
            if (str.Equals("mac"))
                rtnStr = GetMacAdd(rstList);
            else if (str.Equals("ip"))
                rtnStr = GetMachineIP(rstList);
            else if(str.Equals("host"))
                rtnStr = GetHostName(rstList);
            CloseProcess(procName);
        }
        catch
        {
            rtnStr = "";
        }
        return rtnStr;
    }

    private static List<string> executeCmd(string cmdStr, string procName)
    {
        List<string> rstList = new List<string>();
        StringBuilder tbResult = new StringBuilder();

        Process p = new Process();
        p.StartInfo.FileName = procName;//设定要执行的程序名
        p.StartInfo.UseShellExecute = false;//关闭Shell的使用   
        p.StartInfo.RedirectStandardInput = true;//重定向标准输入  
        p.StartInfo.RedirectStandardOutput = true;//重定向标准输出   
        p.StartInfo.RedirectStandardError = true; //重定向错误输出  
        p.StartInfo.CreateNoWindow = true; //设置不显示窗口   
        p.Start(); //启动  
        p.StandardInput.AutoFlush = true;
        p.StandardInput.WriteLine(cmdStr);
        p.StandardInput.WriteLine("exit");
        //strRst = p.StandardOutput.ReadToEnd();

        StreamReader reader = p.StandardOutput; //截取输出流
        string line = reader.ReadLine(); //每次读取一行
        while (!reader.EndOfStream)
        {
            rstList.Add(reader.ReadLine());
        }
        p.WaitForExit(); //等待程序执行完退出进程 
        p.Close();
        reader.Close(); //关闭流
        return rstList;
    }
  
    /// <summary>
    /// 获取mac地址
    /// </summary>
    /// <param name="lst"></param>
    /// <returns></returns>
    private static string GetMacAdd(List<string> lst) {
        string rntStr= "";
        if (lst == null || lst.Count == 0)
            return rntStr;
        foreach (string str in lst)
        {
            if (str.Contains("Physical Address") || str.Contains("物理地址"))
            {
                rntStr = str.Split(':')[1].Trim();
                break;
            }
        }
        return rntStr;
    }

    /// <summary>
    /// 获取主机名
    /// </summary>
    /// <returns></returns>
    public static string GetHostName(List<string> lst)
    {
        string rntStr = "HostName";
        if (lst == null || lst.Count == 0)
            return rntStr;
        foreach (string str in lst)
        {
            if (str.Contains("Host Name"))
            {
                rntStr = str.Split(':')[1].Trim();
                break;
            }
        }
        return rntStr;
    }
    
    /// <summary>
    /// IP
    /// </summary>
    /// <returns></returns>
    public static string GetMachineIP(List<string> lst)
    {
        //IPHostEntry dnstoip = new IPHostEntry();
        //dnstoip = Dns.Resolve("mm56mm.3322.org");
        //return dnstoip.AddressList[0].ToString();
        string rntStr = "IPAddress";
        if (lst == null || lst.Count == 0)
            return rntStr;
        foreach (string str in lst)
        {
            if (str.Contains("IP Address"))
            {
                rntStr = str.Split(':')[1].Trim();
                break;
            }
        }
        return rntStr;
    }
    /// <summary>
    /// 获取CPU
    /// </summary>
    /// <returns></returns>
    public static string GetMachineCPU()
    {

        ManagementClass mc = new ManagementClass("Win32_Processor");
        ManagementObjectCollection moc = mc.GetInstances();

        String strCpuID = null;
        foreach (ManagementObject mo in moc)
        {
            strCpuID = mo.Properties["ProcessorId"].Value.ToString();
            break;
        }
        return strCpuID;

    }
    /// <summary>
    /// 获取硬盘唯一序列号（不是卷标号），可能需要以管理员身份运行程序 
    /// 这个经过测试是唯一的
    /// </summary>
    /// <returns></returns>
    public static string GetHdId()
    {
        ManagementObjectSearcher wmiSearcher = new ManagementObjectSearcher();
        wmiSearcher.Query = new SelectQuery(
            "Win32_DiskDrive",
            "",
            new string[] { "PNPDeviceID", "signature" }
        );
        ManagementObjectCollection myCollection = wmiSearcher.Get();
        ManagementObjectCollection.ManagementObjectEnumerator em =
        myCollection.GetEnumerator();
        em.MoveNext();
        ManagementBaseObject mo = em.Current;
        string id = mo.Properties["signature"].Value.ToString().Trim();
        return id;
    }
    //#endregion


    /// <summary>
    /// 关闭进程
    /// </summary>
    /// <returns></returns>
    private static void CloseProcess(string ProcName)
    {
        ArrayList proList = new ArrayList();
        string tempName = "";
        int begpos;
        int endpos;
        foreach (Process thisProc in Process.GetProcesses())
        {
            tempName = thisProc.ToString();
            begpos = tempName.IndexOf("(") + 1;
            endpos = tempName.IndexOf(")");
            tempName = tempName.Substring(begpos, endpos - begpos);
            proList.Add(tempName);
            if (tempName == ProcName)
            {
                if (!thisProc.CloseMainWindow())
                    thisProc.Kill(); // 当发送关闭窗口命令无效时强行结束进程
            }
        }
    }
}
